var visitor = {};
//Define angular app
var app = angular.module('TaskManager', []);

//controllers
app.controller('taskController', function ($scope) {
    $scope.today = new Date();
    $scope.newTaskContent = null;
    $scope.newTaskName = null;
    $scope.newTask = null;
    $scope.newTaskDate = null;
    $scope.categories = [
        {name: 'Personal'},
        {name: 'Work'},
        {name: 'School'},
        {name: 'Cleaning'},
        {name: 'Other'}
    ];
    $scope.newTaskCategory = $scope.categories;
    $scope.init = function () {
    };

    $(document).ready(function () {
        var ic = new InformationController();
        var iv = new InformationValidator();

        $scope.getNew = function () {
            $.get('information-get', function (data) {
                $scope.saved = data ? data : null;
                $scope.taskItem = ($scope.saved !== null) ? JSON.parse($scope.saved) : [];
                $('.taskInit').click();
            });
        };
        $scope.addNew = function () {
            if (!visitor.name) {
                alert("请选择一个文件");
                return;
            }

            if (iv.validateForm()) {
                if ($scope.newTaskDate == null || $scope.newTaskDate == '') {
                    $scope.taskItem.push({
                        name: visitor.name,
                        description: $scope.newTask,
                        date: "No deadline",
                        category: $scope.newTaskCategory.name,
                    });
                } else {
                    $scope.taskItem.push({
                        name: visitor.name,
                        description: $scope.newTask,
                        date: $scope.newTaskDate,
                        category: $scope.newTaskCategory.name,
                    });
                }

                $scope.newTask = '';
                $scope.newTaskDate = '';
                $scope.newTaskCategory = $scope.categories;

                $.post('information-add', {
                    taskItem: $scope.taskItem.slice(-1)[0],
                    content: visitor.content
                }, function (data, status) {
                    if (status == 'success') ic.onUpdateSuccess();
                    $scope.getNew();
                });
            }
        };

        $scope.deleteTask = function () {
            var indexes = [];
            var completedTask = $scope.taskItem;
            $scope.taskItem = [];
            angular.forEach(completedTask, function (taskItem) {
                if (!taskItem.complete) {
                    $scope.taskItem.push(taskItem);
                } else {
                    indexes.push(taskItem.index);
                }
            });
            $.post('information-delete', {indexes: indexes}, function (data, status) {
                if (status == 'success') {
                    ic.onUpdateSuccess();
                }
                $scope.getNew();
            });
        };

        $scope.publishTask = function () {
            var indexes = [];
            var completedTask = $scope.taskItem;
            angular.forEach(completedTask, function (taskItem) {
                if (taskItem.complete) {
                    indexes.push(taskItem.index);
                }
            });
            $.post('information-publish', {indexes: indexes}, function (data, status) {
                if (status == 'success') {
                    ic.onUpdateSuccess();
                }
            });
        };


        $scope.getNew();
    });
});

//choose a file
$(document).ready(function () {
    var fileTypes = ['pdf'];

    var parseFile = function (e) {
        e.preventDefault();

        var file = e.target.files ? e.target.files[0] : e.dataTransfer.files[0];
        var size = Math.round(file.size / 1048576);
        var fileName = file.name.substring(file.name.lastIndexOf(".") + 1).toLowerCase();

        if (size > 3) {
            alert('当前文件过大！(你当前的文件大小为${size}MB)');
            return;
        }

        if (fileTypes.indexOf(fileName) === -1) {
            alert('请选择${fileTypes.join(', ')}格式文件上传！(你当前的文件格式为${fileName})');
            return;
        }

        notifyFileName(file);
        handleDrop(file);
    };

    var notifyFileName = function (file) {
        var name;
        if (file) {
            name = file.name;
            $('#notify').html(name + " has been chosen");
        } else {
            $('#notify').html("No file chosen");
        }
    }
    var handleDrop = function (file) {
        var reader;
        var workbook;
        if (file) {
            reader = new FileReader;
            reader.onload = function (e) {
                visitor.content = reader.result;
                visitor.name = file.name;
            };
            reader.readAsDataURL(file);
        }
    }

    var target = document.querySelector('#target');

    target.addEventListener('dragenter', function (e) {
        e.preventDefault();
        this.classList.remove('hover');

    });
    target.addEventListener('dragleave', function (e) {
        e.preventDefault();
        this.classList.add('hover');
    });
    target.addEventListener('dragover', function (e) {
        e.preventDefault();
        this.classList.remove('hover');
    });
    target.addEventListener('drop', parseFile);

    var fileInput = document.createElement('input');

    fileInput.type = "file";
    fileInput.onchange = function (e) {
        parseFile(e);
    };

    $('#choose').click(function (e) {
        e.preventDefault();
        fileInput.click(e);
    });
    
    // ------some Tool functions (pure function)
    function isThisMan(name) {
        var user = $("#userUser").val();
        return user ? (user === name) : false;
    }

    if (isThisMan("admin")) {
        $('.taskPublish').show();
    }
});